<template>
  <div>
    <div class="title font14 ma30-15">
      <p>实名认证</p>
    </div>
    <div class="bor7 pa15">
      <el-form
        :model="ruleForm"
        :rules="ruleFormRules"
        ref="ruleForm"
        label-width="100px"
      >
     <el-form-item label="认证人姓名" prop="name"   class="w50 font12">
          <el-input  v-model="ruleForm.name" placeholder="请输入您的姓名"></el-input>
        </el-form-item>

        <el-form-item label="身份证号" prop="idcard"   class="w50 font12">
          <el-input  v-model="ruleForm.idcard" onkeyup="this.value=this.value.replace(/[^\X0-9]/g, '')" placeholder="请输入您身份证号"></el-input>
        </el-form-item>


    <el-form-item label="身份证照片" class="font12 huodonghaibao" >
          <!-- <img src="../../img/2.jpg" alt />
          <img src="../../img/2.jpg" alt /> -->

            <el-row :gutter="20">
            <el-col :span="6" class="p_l_no">
              <div class="grid-content bg-purple">
                <el-upload
                  class="upload-demo"
                  drag
                  action="#"
                  ref="upload"
                  :file-list="files"
                  :http-request="handleUpload"
                  :auto-upload="true"
                >
                  <div class="grid-content bg-purple">
                    <img
                      v-if="imageUrl"
                      :src="imageUrl"
                      v-model="ruleForm.idcard_image1"
                      class="avatar w100"
                    />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </div>

                </el-upload>
              </div>
            </el-col>
            <el-col :span="6" class="p_l_no">
              <div class="grid-content bg-purple font12">
                <div class="bg-purple-text">
                  <p class="colred">温馨提示</p>1、格式要求：原件照片
                  <br />2、支持jpg/jpeg/png/bmp格式的照片，大小不超过1M
                  <div>
                    <!--el-button @click="CancelUpload">取 消</el-button-->
                    <!--el-button
                      type="primary"
                      class="primary"
                      @click="fileChange"
                      >上传海报</el-button-->
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="身份证反面" class="font12 huodonghaibao" >
          <!-- <img src="../../img/2.jpg" alt />
          <img src="../../img/2.jpg" alt /> -->

          <el-row :gutter="20">
            <el-col :span="6"  class="p_l_no">
              <div class="grid-content bg-purple">
                <el-upload
                  class="upload-demo"
                  drag
                  action="#"
                  ref="upload2"
                  :file-list="files2"
                  :http-request="handleUpload2"
                  :auto-upload="true"
                >
                  <div class="grid-content bg-purple">
                    <img
                      v-if="imageUrl2"
                      :src="imageUrl2"
                      v-model="ruleForm.idcard_image2"
                      class="avatar w100"
                    />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </div>

                </el-upload>
              </div>
            </el-col>
            <el-col :span="6" class="p_lr_100">
              <div class="grid-content bg-purple font12">
                <div class="bg-purple-text">
                  <p class="colred">温馨提示</p>1、格式要求：原件照片
                  <br />2、支持jpg/jpeg/png/bmp格式的照片，大小不超过1M
                  <div>
                    <!--el-button @click="CancelUpload2">取 消</el-button>
                    <el-button
                      type="primary"
                      class="primary"
                      @click="fileChange2"
                    >上传照片</el-button
                    -->
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
    <el-form-item>
      <el-button
        type="submit"
        class="baocun"
        @click="handleSubmit">
        确认提交
      </el-button>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: "",
      imageUrl2: "",
      files: [],
      files2: [],
      ruleForm: [],
      ruleFormRules: {
        name: [{ required: true, message: "姓名必填", trigger: "blur" }],
        idcard: [{ required: true, message: "身份证号必填", trigger: "blur" }],
        idcard_image1: [{ required: true, message: "身份证正面图片必填", trigger: "blur" }],
        idcard_image2: [{ required: true, message: "身份证反面图片必填", trigger: "blur" }],
      },
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("图片尺寸 1080*640，.jpg 或 .png格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片尺寸不能超过 4M!");
      }
      return isJPG && isLt2M;
    },
    //提交
    handleSubmit() {
      this.$nextTick(() => {
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            //console.log(this.ruleForm);
            var idcard = this.ruleForm.idcard;
            //定义一个json示例
            if (!idcard) {
              this.$message.error('身份证号不能为空');
              return false;
            }
            if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(idcard)) {
              this.$message.error('你输入的身份证长度或格式错误');
              return false;
            }
            //身份证城市
            var aCity = {
              11: "北京",
              12: "天津",
              13: "河北",
              14: "山西",
              15: "内蒙古",
              21: "辽宁",
              22: "吉林",
              23: "黑龙江",
              31: "上海",
              32: "江苏",
              33: "浙江",
              34: "安徽",
              35: "福建",
              36: "江西",
              37: "山东",
              41: "河南",
              42: "湖北",
              43: "湖南",
              44: "广东",
              45: "广西",
              46: "海南",
              50: "重庆",
              51: "四川",
              52: "贵州",
              53: "云南",
              54: "西藏",
              61: "陕西",
              62: "甘肃",
              63: "青海",
              64: "宁夏",
              65: "新疆",
              71: "台湾",
              81: "香港",
              82: "澳门",
              91: "国外"
            };
            if (!aCity[parseInt(idcard.substr(0, 2))]) {
              this.$message.error('你的身份证地区非法');
              return false;
            }
            // 出生日期验证
            var sBirthday = (
                idcard.substr(6, 4) +
                "-" +
                Number(idcard.substr(10, 2)) +
                "-" +
                Number(idcard.substr(12, 2))
              ).replace(/-/g, "/"),
              d = new Date(sBirthday);
            if (
              sBirthday !=
              d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate()
            ) {
              this.$message.error('身份证上的出生日期非法');
              return false;
            }

            // 身份证号码校验
            var sum = 0,
              weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
              codes = "10X98765432";
            for (var i = 0; i < idcard.length - 1; i++) {
              sum += idcard[i] * weights[i];
            }
            var last = codes[sum % 11]; //计算出来的最后一位身份证号码
            if (idcard[idcard.length - 1] != last) {
              this.$message.error('你输入的身份证号非法');
              return false;
            }

            var url = this.$api + "/api/user/addidcard";
            var jsons = {
              name: this.ruleForm.name,
              idcard: this.ruleForm.idcard,
              idcard_image1: this.ruleForm.idcard_image1,
              idcard_image2: this.ruleForm.idcard_image2
            };

            var that = this;

            this.$axios
              .post(url, jsons)
              .then((res) => {
                //console.log(res.data);
                if (res.data.code == 1) {
                  that.$message({
                    message: res.data.msg,
                    type: "success",
                  });
                  that.getUserInfo();
                } else {
                  that.$message.error(res.data.msg);
                }
              })
              .catch((Error) => {
                //console.log(Error);
                that.$message.error(Error);
              });
          }
        });
      })
    },
    //上传文件开始
    handleUpload(raw) {
      this.files.push(raw.file);
      this.fileChange();
      // //console.log(files);
    },
    async fileChange() {
      if (this.files.length > 1) {
        this.$message.warning(`当前限制只能上传选择 2 个文件`);
        return;
      } else {
      }
      const loading = this.$loading({
        lock: true,
        text: "上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$refs.upload.submit(); // 这里是执行文件上传的函数，其实也就是获取我们要上传的文件
      let random = Math.random();
      let formData = new FormData();
      // formData.append("file", param.file);
      //formData.append("user_id", localStorage.user_id);
      this.files.forEach(function (file) {
        formData.append("file", file); // 因为要上传多个文件，所以需要遍历一下才行
        //不要直接使用我们的文件数组进行上传，你会发现传给后台的是两个Object
      });
      let res = await this.$axios.post(
        this.$api + `/api/common/upload`,
        formData
      );
      //console.log(res);
      // JSON.parse(res)
      if (res.data.code == 1) {
        this.$refs.upload.clearFiles();
        this.files = [];
        let objList = [];
        loading.close();
        this.imageUrl = this.$api + res.data.data.url;
        this.$set(this.ruleForm,'idcard_image1',res.data.data.url);
      } else {
        loading.close();
        this.$message.error("上传文件失败" + res.data.msg);
      }
    },
    handExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    CancelUpload() {
      this.files = [];
      this.$refs.upload.clearFiles();
    },
    handFileSuccess(file) {
      //console.log(file);
      this.files = [];
      this.$refs.upload.clearFiles();
    },
    handleRemove(file, fileList) {
      // //console.log(file, fileList);
      this.files = fileList;
    },
    beforeRemove(file, fileList) {
      // //console.log(file, fileList);
    },

    //上传文件开始2
    handleUpload2(raw) {
      this.files2.push(raw.file);
      this.fileChange2();
      // //console.log(files);
    },
    async fileChange2() {
      if (this.files2.length > 1) {
        //this.$message.warning(`当前限制只能上传选择 1 个文件`);
        return;
      } else {
      }
      const loading = this.$loading({
        lock: true,
        text: "上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$refs.upload2.submit(); // 这里是执行文件上传的函数，其实也就是获取我们要上传的文件
      let random = Math.random();
      let formData = new FormData();
      // formData.append("file", param.file);
      //formData.append("user_id", localStorage.user_id);
      this.files2.forEach(function (file2) {
        formData.append("file", file2); // 因为要上传多个文件，所以需要遍历一下才行
        //不要直接使用我们的文件数组进行上传，你会发现传给后台的是两个Object
      });
      let res = await this.$axios.post(
        this.$api + `/api/common/upload`,
        formData
      );
      //console.log(res);
      // JSON.parse(res)
      if (res.data.code == 1) {
        this.$refs.upload2.clearFiles();
        this.files2 = [];
        let objList = [];
        loading.close();
        this.imageUrl2 = this.$api + res.data.data.url;
        this.$set(this.ruleForm,'idcard_image2',res.data.data.url);
      } else {
        loading.close();
        this.$message.error("上传文件失败" + res.data.msg);
      }
    },
    handExceed2(files2, fileList2) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files2.length} 个文件，共选择了 ${
          files2.length + fileList2.length
        } 个文件`
      );
    },
    CancelUpload2() {
      this.files2 = [];
      this.$refs.upload2.clearFiles();
    },
    handFileSuccess2(file2) {
      //console.log(file2);
      this.files2 = [];
      this.$refs.upload2.clearFiles();
    },
    handleRemove2(file2, fileList2) {
      // //console.log(file, fileList);
      this.files2 = fileList2;
    },
    beforeRemove2(file2, fileList2) {
      // //console.log(file, fileList);
    },
    getUserInfo() {
      var that = this;
      this.$axios
        .get(this.$api + "//api/user/userinfo")
        .then(function (response) {
          that.ruleForm = response.data.data;
          //console.log("info", response.data.data);
        })
        .catch(function (error) {
          //console.log(error);
        });
    },

  },
  mounted() {
    this.getUserInfo();
  },
};
</script>

<style scoped>
html {
  height: 100% !important;
  overflow-y: hidden !important;
}.p_l_no {
  padding-left: 0 !important;
}
@media (max-width:767px) {
  .p_l_no {
    padding-left: 10px !important;
  }
  .w50 {width: 100%;}
}
</style>
